import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yysk_app/model/order_model/get_pay_token_model.dart';
import 'package:yysk_app/model/user_prop_model/list_by_propId_result_model.dart';
import 'package:yysk_app/model/user_prop_model/list_by_propId_send_model.dart';
import 'package:yysk_app/net/api/order_api.dart';
import 'package:yysk_app/net/api/product_api.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/main/main_page.dart';
import 'package:yysk_app/pages/nft_pages/danation/danation_choose_goods_controller.dart';
import 'package:yysk_app/pages/nft_pages/pay_pages/confirm_payment/confirm_payment_page.dart';
import 'package:yysk_app/pages/nft_pages/pay_pages/result_payment/result_payment_page.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_exchange_psw.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_page.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_real_name_auth_page.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/dialog_widget.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:oktoast/oktoast.dart';

class PayWayModel {
  String? name;
  String? url;
  String? price;
  RxBool isChoose = false.obs;
  PayWayModel({this.name, this.url, this.price, required this.isChoose});
}

class DanationConfirmController extends GetxController {
  var dataList = <ListByPropIdSendModel>[].obs;
  var addressController = TextEditingController();
  final list = [].obs;
  final type = '1'.obs; //app ，臻转赠
  final getTokentype = '1'.obs; //app ，臻转赠
  final url = ''.obs; //图片
  final propId = 0.obs; //
  final boxId = 0.obs; //
  final collectionId = 0.obs; //
  final drawerCount = 0.obs;
  final securityPassword = ''.obs;
  final transferType = ''.obs;
  final transferTypeWay = 1.obs; //1藏品 2盲盒3道具
  @override
  void onInit() {
    super.onInit();
    list.value = Get.parameters['list'] ?? (Get.arguments['list'] ?? []);
    getTokentype.value =
        Get.parameters['getTokentype'] ?? (Get.arguments['getTokentype'] ?? []);
    url.value = Get.parameters['url'] ?? (Get.arguments['url'] ?? '');
    propId.value = Get.parameters['propId'] ?? (Get.arguments['propId'] ?? 0);
    boxId.value = Get.parameters['boxId'] ?? (Get.arguments['boxId'] ?? 0);
    collectionId.value =
        Get.parameters['collectionId'] ?? (Get.arguments['collectionId'] ?? 0);
    transferTypeWay.value =
        Get.parameters['transferTypeWay'] ??
        (Get.arguments['transferTypeWay'] ?? 1);
    type.value = Get.parameters['type'] ?? (Get.arguments['type'] ?? '1');

    consoleLog('${list.value}==list');
    consoleLog('${type.value}==type');
    consoleLog('${url.value}==url');
    consoleLog('${boxId.value}==boxId');
    if (transferTypeWay.value == 1) {
      getInfoCollection().then((e) {
        if (dataList.isNotEmpty) {
          dataList[0].isSelect = true;
          transferType.value = dataList[0].transferType ?? '';
        }
      });
    } else if (transferTypeWay.value == 2) {
      getInfoBlind().then((e) {
        if (dataList.isNotEmpty) {
          dataList[0].isSelect = true;
          transferType.value = dataList[0].transferType ?? '';
        }
      });
    } else {
      getInfoProp().then((e) {
        if (dataList.isNotEmpty) {
          dataList[0].isSelect = true;
          transferType.value = dataList[0].transferType ?? '';
        }
      });
    }
  }

  @override
  void onClose() {
    super.onClose();
  }

  Future getInfoProp() async {
    await http.netFetch<List<ListByPropIdSendModel>>(
      ProductApi.transferConsumption,
      method: Method.post,
      params: {
        "propId": propId.value,
        // ignore: invalid_use_of_protected_member
        "userPropIdList": list.value,
      },
      success: (res) {
        if (res.code == 200) {
          dataList.value = res.data ?? [];
        }
      },
    );
  }

  Future getInfoBlind() async {
    await http.netFetch<List<ListByPropIdSendModel>>(
      ProductApi.userBoxTransferConsumption,
      method: Method.post,
      params: {
        "boxId": boxId.value,
        // ignore: invalid_use_of_protected_member
        "userBoxIdList": list.value,
      },
      success: (res) {
        if (res.code == 200) {
          dataList.value = res.data ?? [];
        }
      },
    );
  }

  Future getInfoCollection() async {
    await http.netFetch<List<ListByPropIdSendModel>>(
      ProductApi.userCollectionTransferConsumption,
      method: Method.post,
      params: {
        "collectionId": collectionId.value,
        // ignore: invalid_use_of_protected_member
        "userCollectionIdList": list.value,
        "platform": type.value == '1' ? 'INTERNAL' : 'EXTERNAL',
      },
      success: (res) {
        if (res.code == 200) {
          dataList.value = res.data ?? [];
        }
      },
    );
  }

  sub() {
    if (getTokentype.value == '1') {
      subCollection();
    } else if (getTokentype.value == '2') {
      subBlind();
    } else {
      subProp();
    }
  }

  Future subProp() async {
    await http.netFetch<ListByPropIdResultModel>(
      ProductApi.doTransfer,
      method: Method.post,
      params: {
        "propId": propId.value,
        // ignore: invalid_use_of_protected_member
        "userPropIdList": list.value,
        "securityPassword": securityPassword.value,
        "transferType": transferType.value,
        'receiveAddress': addressController.text,
      },
      success: (res) {
        if (res.code == 200) {
          if (res.data?.needPay == true) {
            getPayTokenProp(res.data?.orderId);
            // if (getTokentype.value == '1') {
            //   getPayTokenCollection(res.data?.orderId);
            // } else if (getTokentype.value == '2') {
            //   getPayTokenBlind(res.data?.orderId);
            // } else {
            //   getPayTokenProp(res.data?.orderId);
            // }
          } else {
            showToast('操作成功');
            Get.back();
          }
        }
      },
    );
  }

  Future subBlind() async {
    await http.netFetch<ListByPropIdResultModel>(
      ProductApi.userBoxDoTransfer,
      method: Method.post,
      params: {
        "boxId": boxId.value,
        // ignore: invalid_use_of_protected_member
        "userBoxIdList": list.value,
        "securityPassword": securityPassword.value,
        "transferType": transferType.value,
        'receiveAddress': addressController.text,
      },
      success: (res) {
        if (res.code == 200) {
          if (res.data?.needPay == true) {
            getPayTokenBlind(res.data?.orderId);
          } else {
            showToast('操作成功');
            Get.back();
          }
        }
      },
    );
  }

  Future subCollection() async {
    await http.netFetch<ListByPropIdResultModel>(
      ProductApi.userCollectionDoTransfer,
      method: Method.post,
      params: {
        "collectionId": collectionId.value,
        // ignore: invalid_use_of_protected_member
        "userCollectionIdList": list.value,
        "securityPassword": securityPassword.value,
        "transferType": transferType.value,
        'receiveAddress': addressController.text,
        "platform": type.value == '1' ? 'INTERNAL' : 'EXTERNAL',
      },
      success: (res) {
        if (res.code == 200) {
          if (res.data?.needPay == true) {
            getPayTokenCollection(res.data?.orderId);
            // if (getTokentype.value == '1') {
            //   getPayTokenCollection(res.data?.orderId);
            // } else if (getTokentype.value == '2') {
            //   getPayTokenBlind(res.data?.orderId);
            // } else {
            //   getPayTokenProp(res.data?.orderId);
            // }
          } else {
            showToast('操作成功');
            Get.back();
          }
        }
      },
    );
  }

  //获取令牌
  Future<dynamic> getPayTokenCollection(dynamic sn) async {
    try {
      http.netFetch<GetPayTokenModel>(
        ProductApi.getPayTokenCollection,
        method: Method.post,
        params: {'orderId': sn},
        success: (result) {
          Get.toNamed(
            '${ConfirmPaymentPage.path}?cashierToken=${result.data?.cashierToken}&accessToken=${result.data?.accessToken}&businessType=VIRTUAL_GOODS&clientType=web',
            arguments: {
              'cashierToken': result.data?.cashierToken,
              'accessToken': result.data?.accessToken,
              'businessType': 'DEBUT',
            },
          );
          // 在 Web 环境下调用 JavaScript
          // window.location.href =
          //     '${Env.envConfig.envPayUrl}?cashierToken=${result.data?.cashierToken}&accessToken=${result.data?.accessToken}&businessType=PHYSICAL_GOODS&clientType=web';
          return result;
        },
      );
    } catch (e) {
      consoleLog(e.toString());
    }
  }

  Future<dynamic> getPayTokenBlind(dynamic sn) async {
    try {
      http.netFetch<GetPayTokenModel>(
        ProductApi.getPayTokenBlind,
        method: Method.post,
        params: {'orderId': sn},
        success: (result) {
          Get.toNamed(
            '${ConfirmPaymentPage.path}?cashierToken=${result.data?.cashierToken}&accessToken=${result.data?.accessToken}&businessType=VIRTUAL_GOODS&clientType=web',
            arguments: {
              'cashierToken': result.data?.cashierToken,
              'accessToken': result.data?.accessToken,
              'businessType': 'DEBUT',
            },
          );
          // 在 Web 环境下调用 JavaScript
          // window.location.href =
          //     '${Env.envConfig.envPayUrl}?cashierToken=${result.data?.cashierToken}&accessToken=${result.data?.accessToken}&businessType=PHYSICAL_GOODS&clientType=web';
          return result;
        },
      );
    } catch (e) {
      consoleLog(e.toString());
    }
  }

  Future<dynamic> getPayTokenProp(dynamic sn) async {
    try {
      http.netFetch<GetPayTokenModel>(
        ProductApi.getPayTokenProp,
        method: Method.post,
        params: {'orderId': sn},
        success: (result) {
          Get.toNamed(
            '${ConfirmPaymentPage.path}?cashierToken=${result.data?.cashierToken}&accessToken=${result.data?.accessToken}&businessType=VIRTUAL_GOODS&clientType=web',
            arguments: {
              'cashierToken': result.data?.cashierToken,
              'accessToken': result.data?.accessToken,
              'businessType': 'DEBUT',
            },
          );
          // 在 Web 环境下调用 JavaScript
          // window.location.href =
          //     '${Env.envConfig.envPayUrl}?cashierToken=${result.data?.cashierToken}&accessToken=${result.data?.accessToken}&businessType=PHYSICAL_GOODS&clientType=web';
          return result;
        },
      );
    } catch (e) {
      consoleLog(e.toString());
    }
  }

  //去实名
  toSm({required BuildContext context}) async {
    await showConfirmDialog(
      context: context,
      message: '请先完成实名认证',
      messages: [],
      fontSize: 16,
      actions: [
        ActionModel(
          label: '取消',
          colorStart: AppColors.backgroundColorGreyF8,
          colorEnd: AppColors.backgroundColorGreyF8,
          fontColor: AppColors.fontColor,
          onPressed: () {},
        ),
        ActionModel(
          label: '立即认证',
          onPressed: () {
            Get.toNamed(SettingRealNameAuthPage.path);
          },
        ),
      ],
    );
  }

  //是否开通交易密码
  Future<dynamic> isSetPayPassword() async {
    try {
      showConfirmDialog(
        context: Get.context!,
        message: '请先设置交易密码',
        messages: [],
        fontSize: 16,
        actions: [
          ActionModel(label: '取消', onPressed: () {}),
          ActionModel(
            label: '前往设置',
            onPressed: () {
              Get.toNamed(ChangeExchangePassword.path);
            },
          ),
        ],
      );
    } catch (e) {
      debugPrint(e.toString());
    }
  }
}
